package cn.leftsite.netty.test.preset;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLEngine;

/**
 * @author wangjinqiang
 * @date 2019-05-30
 */
public class SslChannelInitializer extends ChannelInitializer<Channel> {

    private final SslContext sslContext;
    private final boolean startTls;

    /**
     * @param sslContext 传入要使用的 SslContext
     * @param startTls   如果设置为 true 第一个写入的消息将不会被加密 (客户端应该设置为true)
     */
    public SslChannelInitializer(SslContext sslContext, boolean startTls) {
        this.sslContext = sslContext;
        this.startTls = startTls;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {
        // 对于每个SslHandler 实例，都使用Channel 的ByteBuf-Allocator 从SslContext 获取一个新的SSLEngine
        SSLEngine sslEngine = sslContext.newEngine(ch.alloc());
        // 将SslHandler 作为第一个ChannelHandler 添加到ChannelPipeline 中
        ch.pipeline().addFirst("ssl", new SslHandler(sslEngine, startTls));
    }
}
